﻿using UnityEngine;
using System.Collections;

public delegate void ReachDelegate();

public class SimpleMove : MonoBehaviour {
	public Vector3 startPosition;
	public Vector3 destPosition;
	public float speed = 4f;
	public ReachDelegate onReachDestination;

	private Vector3 _direction;

	void Start () {
		init ();
	}

	public void move(Vector3 startPos, Vector3 endPos)
	{
		this.enabled = true;
		startPosition = startPos;
		destPosition = endPos;
		init ();
	}
	
	// Update is called once per frame
	void Update () {
		bool isReached = false;
		Vector3 moveOffset = _direction * speed * Time.deltaTime;
		Vector3 movePosition = transform.position + moveOffset;

		Vector3 dir = destPosition - movePosition;

		if (Vector3.Dot (dir, _direction) < 0) {
			movePosition = destPosition;
			isReached = true;
		}

		transform.position = movePosition;
		if (isReached) {
			this.enabled = false;

			if (onReachDestination != null){
				onReachDestination();
			}
		}
	}

	private void init()
	{
		_direction = destPosition - startPosition;
		_direction.Normalize ();
		
		transform.position = startPosition;
	}
	
}
